//
//  HOPPlaceholderTextView.swift
//  WB01
//
//  Created by HOP on 15/12/29.
//  Copyright © 2015年 HOP. All rights reserved.
//

import UIKit

class HOPPlaceholderTextView: UITextView {

    // MARK: - 属性
    /// 要显示的占位文本
    var placeholderText: String? {
        didSet {// 将占位文本设置给 placeholderLabel
            placeholderLabel.text = placeholderText
            placeholderLabel.sizeToFit()
        }
     
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
        prepareUI()
    }
    deinit {
    // 移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // 文字发生改变
    func textDidChange() {
        placeholderLabel.hidden = hasText()
      }
    // MARK: - 准备UI
    private func prepareUI() {
    // 添加子控件
    self.addSubview(placeholderLabel)
    // 添加约束,如果这个Label想给其他工程使用,最好少依赖第三方框架
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
     // 顶部和父控件顶部重合,有偏移
    addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    // 左边和父控件的左边重合,有偏移
    addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
    }
    
      // MARK: - 懒加载
    /// 占位文本的label,最好是不要把placeholderLabel直接暴露出去.暴露出去后,别人有太多的修改权利
    private lazy var placeholderLabel: UILabel = {
    // 设置占位文本
    let placeholderLabel = UILabel()
        placeholderLabel.font = UIFont.systemFontOfSize(18)
        placeholderLabel.textColor = UIColor.lightGrayColor()
    return placeholderLabel
    
    }()
}
